package com.trg.designmodel.singleleton;

/**
 * @ClassName: SingleLetonTest06
 * @Description: 单例设计模式-懒汉式（双重检查）
 * @Author: tangrg
 * @Date: 2021/6/30 16:53
 * @Version: 1.0
 * @Return:
 **/
public class SingleLetonTest06 {

    public static void main(String[] args) {
        SingleLeton06 instance = SingleLeton06.getInstance();
        SingleLeton06 instance2 = SingleLeton06.getInstance();
        System.out.println("单例设计模式-懒汉式（双重检查）");
        System.out.println(instance == instance2);
        System.out.println("instance:" + instance.hashCode());
        System.out.println("instance2:" + instance2.hashCode());
    }
}

class SingleLeton06 {
    private static SingleLeton06 instance;

    private SingleLeton06() {

    }

    //提供一个静态的公有方法，加入双重检查代码，解决线程安全问题, 同时解决懒加载问题
    public static SingleLeton06 getInstance() {
        if (instance == null) {
            synchronized (SingleLeton06.class) {
                if (instance == null) {
                    instance = new SingleLeton06();
                }
            }
        }
        return instance;
    }
}
